package org.ctstudio.oa.duty.dao;

import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Time;
import java.util.List;

import javax.sql.DataSource;

import org.apache.ibatis.jdbc.SQL;
import org.ctstudio.oa.duty.bean.DutyRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class DutyBatchDAO {
  private JdbcTemplate jdbcTemplate;

  @Autowired
  public void setDataSource(DataSource dataSource) {
    this.jdbcTemplate = new JdbcTemplate(dataSource);
  }

  private static String getSql() {
    SQL sql = new SQL();
    sql.UPDATE("duty.dutyrecords");
    sql.SET("signInTime=?");
    sql.SET("signOutTime=?");
    sql.SET("overTimeSecond=?");
    sql.SET("late=?");
    sql.SET("leaveEarly=?");
    sql.WHERE("signDate=?");
    sql.WHERE("uid=?");
    return sql.toString();
  }

  public int[] batchUpgradeDutyRecord(final List<DutyRecord> list) {
    String sql = getSql();
    return jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
      public void setValues(PreparedStatement ps, int i) throws SQLException {
        int col = 0;
        DutyRecord item = list.get(i);
        ps.setTime(++col, Time.valueOf(item.getSignInTime()));
        ps.setTime(++col, Time.valueOf(item.getSignOutTime()));
        ps.setLong(++col, item.getWorkTimeSecond());
        ps.setLong(++col, item.getOverTimeSecond());
        ps.setBoolean(++col, item.isLate());
        ps.setBoolean(++col, item.isEarly());
        ps.setDate(++col, Date.valueOf(item.getSignDate()));
        ps.setString(++col, item.getUid());
      }

      public int getBatchSize() {
        return list.size();
      }
    });
  }
}
